home *** CD-ROM | disk | FTP | other *** search
/ The Atari Compendium / The Atari Compendium (Toad Computers) (1994).iso / files / prgtools / editors / mutt / me2s_pl7.zoo / mu_edit2 / util / fxpand.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-07-05  |  14.5 KB  |  513 lines

  1. static char rcsid[] = "$Id: fxpand.c,v 1.1 1992/09/06 19:31:32 mike Exp $";
  2.  
  3. /* $Log: fxpand.c,v $
  4.  * Revision 1.1  1992/09/06  19:31:32  mike
  5.  * Initial revision
  6.  *
  7.  */
  8.  
  9. #if 0        /* there are star-slashes in the comment below */
  10. /* fxpand.c : fxpand(): expand file names
  11.  * Input:
  12.  *   name:  A file name which can contain: ?, \, [], [^] and *
  13.  *     If name ends with "." (eg *.) then only names with no extensions will
  14.  *       be matched.
  15.  *     If name beings with ~ then:  "~/" expands to "$(HOME)/" and "~name"
  16.  *     expands to "<home directory of name>".
  17.  *     MS-DOS:  \ is same as /.  Does not quote.
  18.  *     UNIX: \ quotes the next character.
  19.  *     ATARI (from jwahar r.  bammi (bammi@cadence.com)):
  20.  *       Like MS-DOS, \ == /, except that we have the POSIX opendir() etc.
  21.  *   onlyone: If TRUE return the first match otherwise all matches are
  22.  *     returned.  For example, this controls how "*" is expanded.
  23.  *   nopath:  If TRUE, only return the matching file names.  Otherwise
  24.  *     return the path and name.  For example, "/foo/bar" => "bar".
  25.  *   slash_dir:  If TRUE, append a slash to the end of a file name if the
  26.  *     file is a directory.  For example, input of "dir" would generate
  27.  *     "dir/".
  28.  *   name_heap:
  29.  *     NULL: Call process_fname.
  30.  *     Pointer to char[]:  Stuff the file names in here.  The names are
  31.  *    separated by a blank and there are no trailing blanks.
  32.  *   process_fname:  A function which is passed a char *.  The string
  33.  *       contains the expanded file name.
  34.  *     Returns:  0 if all OK, >1 an error to be returned by fxpand().
  35.  * Output:
  36.  *   0:  All OK
  37.  *   1:  Something screwed up.  Most likely the name is bad.
  38.  *   n:  An error code returned by process_fname().
  39.  * 
  40.  * Notes:
  41.  *   When compiled on Apollo, this routine also works with the Domain/OS
  42.  *     "//" notation.  This is mostly luck - I don't collapse "/"s and a
  43.  *     relaxed check lets this work.
  44.  *   Input error checking is pretty grim.
  45.  * Unix Notes:
  46.  *   When wildcard matching, hidden files (those that start with ".")  are
  47.  *     skipped unless you ask to see them.  To match ".fred", you could use
  48.  *     ".f*".  To match "fred/.sam/geo", you would need something like
  49.  *     "fred/.s*/g*".
  50.  *   When appending slashes (slash_dir), expanding something like "*" can be
  51.  *     very slow.  This is because I have to stat() to find out if the file
  52.  *     is a directory and stat() can take a long time to stat files over nfs
  53.  *     mounts, follow links, etc.
  54.  * 
  55.  * Craig Durland
  56.  *
  57.  * Do not delete this double quote! " (You are not expected to understand this)
  58.  */
  59. #endif
  60.  
  61. /* Copyright 1989, 1990, 1991 Craig Durland
  62.  *   Distributed under the terms of the GNU General Public License.
  63.  *   Distributed "as is", without warranties of any kind, but comments,
  64.  *     suggestions and bug reports are welcome.
  65.  */
  66.  
  67. #define _HPUX_SOURCE        /* for ANSI C on HP-UX */
  68. #define _BSD_SOURCE        /* for ANSI C on Apollo BSD */
  69. #define _POSIX_SOURCE        /* for ANSI C on IBM AIX */
  70.  
  71. #include <stdio.h>
  72. #include "os.h"
  73. #include "const.h"
  74.  
  75. extern char *strchr(), *getenv(), *strcpy(), *strcat();
  76.  
  77. static char *name_list;
  78. static int prepend_blank;
  79. static int stuff_name(name) char *name;
  80. {
  81.   if (prepend_blank) strcat(name_list," ");
  82.   else prepend_blank = TRUE;
  83.  
  84.   strcat(name_list,name);
  85.   return 0;
  86. }
  87.  
  88. #if MSDOZ
  89.  
  90. #define SLASH    "/"        /* "/" or "\\", your preference */
  91.  
  92.     /* A note about MS-DOS:  Its file find routines are brain dead:  If you
  93.      *   ask for a directory, you will get all file types.  Also, since
  94.      *   there is a file type==0, you can't just use AND to filter out
  95.      *   unwanted types.  What a pain in the butt!
  96.      */
  97.  
  98. #include <dos.h>
  99. #ifdef __TSC__         /* ibmdir.h has definitions for Lattice  C structures */
  100. #include "ibmdir.h"
  101. #include "char.h"
  102. #endif    /* __TSC__ */
  103.  
  104. typedef struct FILEINFO FI;    /* in dos.h */
  105.  
  106. #define FATTR (FA_ARCHIVE | FA_RD_ONLY | FA_DIRECTORY)    /* file attributes */
  107.  
  108.  
  109. fxpand(name, onlyone,nopath,slash_dir, name_heap,process_fname)
  110.   char *name,*name_heap; pfi process_fname;
  111. {
  112.   char path[128], word[100], *ptr, *qtr, tbuf[128];
  113.   FI de;
  114.   int atend, eval, found, needadot, path_len, s;
  115.  
  116.   if (name_heap)    /* store the found file names in name_heap */
  117.   {
  118.     process_fname = stuff_name;
  119.     *(name_list = name_heap) = '\0';
  120.     prepend_blank = FALSE;
  121.   }
  122.  
  123.   *path = '\0';
  124.   if (*name == '~')
  125.   {
  126.     name++;
  127.     if (ptr = getenv("HOME")) strcpy(path,ptr);
  128.   }
  129.   else
  130.     if (name[1] == ':')
  131.     { strncpy(path,name,2); path[2] = '\0'; name += 2; }
  132.  
  133.  
  134.   atend = FALSE; needadot = FALSE;
  135.   while (!atend)
  136.   {
  137.     atend = get_dpart(&name,word,&eval);
  138.     path_len = strlen(path);
  139. uppercase(word);    /* Since the directory entries are uppercase */
  140.     if (eval)            /* wildcards in need of expansion */
  141.     {
  142. if (word[strlen(word)-1] == '.') needadot = TRUE;
  143.       found = FALSE;
  144.       ptr = path +path_len; strcpy(ptr,"*.*");
  145.  
  146.       if (dfind(&de,path,FATTR)) return 1;    /* No files found */
  147.       *ptr = '\0';        /* get rid of "*.*" */
  148.       do        /* look at all entries in this directory */
  149.       {
  150.     if (!atend)            /* only care about directories */
  151.       { if (de.attr != FA_DIRECTORY) continue; }
  152.         else
  153.       if (de.attr &&    /* if de.attr==0, its a regular old file */
  154.           (de.attr & FATTR) == 0) continue;
  155.  
  156.     ptr = qtr = de.name;
  157. if (needadot && !strchr(ptr,'.')) ptr = strcat(strcpy(tbuf,ptr),".");
  158.     if (*qtr != '.' && wildmat(ptr,word))    /* ignore . & .. */
  159.     {
  160.       found = TRUE;
  161.       if (!atend)        /* something like foo/<you are here>/bar */
  162.       {
  163.         strcat(strcat(path,qtr), SLASH);
  164.         break;
  165.       }
  166.       else            /* something like foo/<you are here> */
  167.       {
  168.         strcpy(path +path_len, qtr);
  169.         s = procz(process_fname, slash_dir && (de.attr == FA_DIRECTORY),
  170.             path, nopath ? path_len : 0);
  171.         path[path_len] = '\0';
  172.         if (s) return s;
  173.         if (onlyone) break;
  174.       }
  175.     }
  176.       } while (!dnext(&de));
  177.       if (!found) return 1;
  178.     }
  179.     else
  180.     {
  181.       strcpy(path + path_len, word);
  182.       if (atend)    /* all done */
  183.     return procz(process_fname, slash_dir && is_dir(path),
  184.             path, nopath ? path_len : 0);
  185. /* ??? if (!is_dir(path)) return 1; /* Make sure path is real */
  186.     } 
  187.   }    /* end while */
  188.   return 0;
  189. }
  190.  
  191. static int procz(process_fname, slash_it, path, path_len)
  192.   pfi process_fname; char *path;
  193. {
  194.   if (slash_it && (path[path_len] != '\0')) strcat(path, "/");
  195.   return (*process_fname)(path + path_len);
  196. }
  197.  
  198.     /* 
  199.      * Notes:
  200.      *   For some (unknown to me) reason, FA_DIRECTORY matches everything,
  201.      *     not just directories.
  202.      * WARNING:
  203.      *   This routine changes the DTA.  If you are in the middle of a
  204.      *     dfind/dnext loop, this will mess that up.
  205.      */
  206. static int is_dir(path) char *path;
  207. {
  208.   FI de;
  209.  
  210.   return (!dfind(&de,path,FA_DIRECTORY) && (de.attr == FA_DIRECTORY));
  211. }
  212.  
  213.  
  214.  
  215.     /* MS-DOS stuff for get_dpart() */
  216. #define ASLASH        case '/': case '\\'
  217. #define GOTTA_EVAL    case '?': case '[': case '*'
  218.  
  219. #endif    /* MSDOZ */
  220.  
  221.  
  222. #if ATARI    /* Atari has Posix opendir(), etc */
  223. #undef  POSIX_OS
  224. #define POSIX_OS 1    /* turn on POSIX and UX_OS */
  225. #endif    /* ATARI */
  226.  
  227.  
  228.  
  229.  
  230.  
  231. #if UX_OS    /* and Atari */
  232.  
  233. #define BADGETPW 1    /* 1 if system getpw... routines are screwed up */
  234.  
  235. #include <sys/types.h>
  236. #include <pwd.h>
  237. #include <sys/stat.h>
  238.  
  239.     /* Posix, SysV: HP-UX, Apollo SysV, DEC, Atari  */
  240.     /* defined(POSIX) is a DECism */
  241. #if POSIX_OS || SYSV_OS || defined(POSIX)
  242. #include <dirent.h>
  243. #else        /* Pure BSD: Apollo bsd4.3 */
  244. #include <sys/dir.h>
  245. #endif
  246.  
  247.  
  248. static int get_dpart(), getpwhome(), procz(), is_dir();
  249.  
  250.  
  251.     /* cases to check:
  252.      *   "~", "~fred", "/", "~/", ""
  253.      */
  254. fxpand(name, onlyone,nopath,slash_dir, name_heap,process_fname)
  255.   char *name,*name_heap; pfi process_fname;
  256. {
  257.   char path[512], word[256], *ptr, *qtr, tbuf[256];
  258.   DIR *dir;
  259. #if POSIX_OS || SYSV_OS || defined(POSIX)
  260.   struct dirent *dtr;
  261. #else        /* Apollo bsd4.3, (some)DEC */
  262.   struct direct *dtr;
  263. #endif
  264.   int
  265.     atend, needadot,
  266.     eval, found, path_len, s,
  267.     skip_dot_files;        /* ignore names starting with "." */
  268.   struct passwd *pd;
  269.  
  270.   if (name_heap)    /* store the found file names in name_heap */
  271.   {
  272.     process_fname = stuff_name;
  273.     *(name_list = name_heap) = '\0';
  274.     prepend_blank = FALSE;
  275.   }
  276.  
  277.   *path = '\0';
  278.   if (*name == '~')        /* csh/ksh home directory expansion */
  279.   {
  280.     name++;
  281.     if (ISSLASH(*name) || *name == '\0')    /* ~/foo/bar or ~ */
  282.     {
  283.       if (ptr = getenv("HOME")) strcpy(path,ptr);
  284.       else        /* no $HOME, see if the OS knows */
  285.       {
  286. #if BADGETPW
  287.     return 1;    /* !!! a sleeze */
  288. #else
  289.     if ((pd = getpwuid(getuid())) == NULL) return 1;
  290.     strcpy(path,pd->pw_dir);
  291. #endif    /* BADGETPW */
  292.       }
  293.     }
  294.     else            /* ~fred => user freds' home directory */
  295.     {
  296.       atend = get_dpart(&name,word,&eval);
  297.       if (eval) return 1;        /* no wildcards allowed in user name */
  298.       name--;
  299.       if (!atend) word[strlen(word)-1] = '\0';    /* remove "/" from  "~fred/" */
  300. #if BADGETPW
  301.       if (!getpwhome(word)) return 1;
  302.       strcpy(path,word);
  303. #else
  304.       if ((pd = getpwnam(word)) == NULL) return 1;
  305.       strcpy(path,pd->pw_dir);
  306. #endif    /* BADGETPW */
  307.     }
  308.   }
  309.  
  310.     /* at this point, maybe: strlen(path)!=0 && strlen(name)==0 */
  311.  
  312.   atend = FALSE; needadot = FALSE;
  313.   while (!atend)
  314.   {
  315.     atend = get_dpart(&name,word,&eval);
  316.     skip_dot_files = (*word != '.');    /* ".fred" means look at dot files */
  317.     path_len = strlen(path);
  318.     if (eval)            /* wildcards in need of expansion */
  319.     {
  320. if (word[strlen(word)-1] == '.') needadot = TRUE;
  321.       found = FALSE;
  322.       if ((dir = opendir(path_len == 0 ? "." : path)) == NULL) return 1;
  323.       while (TRUE)        /* look at all entries in this directory */
  324.       {
  325.     if ((dtr = readdir(dir)) == NULL) break;
  326.     ptr = qtr = dtr->d_name;
  327.     if (skip_dot_files && *ptr == '.') continue;
  328. if (needadot && !strchr(ptr,'.')) ptr = strcat(strcpy(tbuf,ptr),".");
  329.     if (wildmat(ptr,word))
  330.     {
  331.       if (!atend)        /* something like foo/<you are here>/bar */
  332.       {
  333.         strcpy(path + path_len, qtr);
  334.             /* make sure its a real directory */
  335.         if (is_dir(path)) { strcat(path,"/"); found = TRUE; break; }
  336.       }
  337.       else            /* something like foo/<you are here> */
  338.       {
  339.         found = TRUE;
  340.         strcpy(path +path_len, qtr);
  341.         s = procz(process_fname, slash_dir, path, nopath ? path_len : 0);
  342.         path[path_len] = '\0';
  343.         if (s) { closedir(dir); return s; }
  344.         if (onlyone) break;
  345.       }
  346.     }
  347.       }        /* end while (TRUE) */
  348.       closedir(dir);
  349.       if (!found) return 1;
  350.     }
  351.     else    /* No wildcards: something like: .../bar/... or .../bar */
  352.     {        /* word may == "" (for input like "~fred") */
  353.       strcpy(path + path_len, word);
  354.       if (atend)    /* all done */
  355.     return procz(process_fname, slash_dir, path, nopath ? path_len : 0);
  356.  
  357. /* ??? if (!is_dir(path)) return 1; /* Make sure path is real */
  358.     }
  359.   }        /* end while */
  360.   return 0;
  361. }
  362.  
  363.  
  364.     /* Input:
  365.      *   process_fname:  pointer to function to call
  366.      *   slash_dir: TRUE:  if path is a directory, append a slash
  367.      *   path:  Full path name
  368.      *   path_len:  offset in path.  Used if what to pass just part of path
  369.      *     to process_fname.
  370.      * Returns:
  371.      *   What ever process_fname returns.
  372.      * Notes:
  373.      *   Need to check path[path_len] before appending a slash because:  if
  374.      *     don't want a path (path_len != 0) and no name (eg expanding "~"),
  375.      *     would process_fname("/") which is not what is expected.
  376.      */
  377. static int procz(process_fname, slash_dir, path, path_len)
  378.   pfi process_fname; char *path;
  379. {
  380.   if (slash_dir && (path[path_len] != '\0') && is_dir(path))
  381.     strcat(path, "/");
  382.   return (*process_fname)(path + path_len);
  383. }
  384.  
  385.  
  386. static int is_dir(path) char *path;
  387. {
  388.   struct stat sbuf;
  389.  
  390.   if (stat(path,&sbuf)) return FALSE;
  391.     /* make sure its a directory */
  392. #ifdef S_ISDIR
  393.   return S_ISDIR(sbuf.st_mode);
  394. #else
  395.   return ((sbuf.st_mode & 0170000) == 040000);
  396. #endif    /* S_ISDIR */
  397. }
  398.  
  399.  
  400. #if BADGETPW
  401.     /* Get the home directory out of the password file.
  402.      * Only use this if the system getpw... routines are
  403.      *   screwed up.
  404.      */
  405. static int getpwhome(name) char *name;
  406. {
  407.   char buf[256], *ptr;
  408.   FILE *fptr;
  409.   int n, s = FALSE;
  410.  
  411.   if ((fptr = fopen("/etc/passwd","r")) == NULL) return FALSE;
  412.   while (fgets(buf,255,fptr))
  413.   {
  414.     for (ptr = buf; *ptr != ':'; ptr++) ; *ptr = '\0';
  415.     if (strcmp(name,buf)) continue;
  416.     for (n = 0; n < 4; ptr++) if (*ptr == ':') n++;
  417.     while (*ptr != ':') *name++ = *ptr++;   *name = '\0';
  418.     s = TRUE;
  419.     break;
  420.   }
  421.   fclose(fptr);
  422.   return s;
  423. }
  424. #endif    /* BADGETPW */
  425.  
  426. #if ATARI    /* Atari stuff for get_dpart(), same as MS-DOS */
  427. #define ASLASH        case '/': case '\\'
  428. #define GOTTA_EVAL    case '?': case '[': case '*'
  429. #else
  430.     /* UNIX stuff for get_dpart() */
  431. #define ASLASH        case '/'
  432. #define GOTTA_EVAL    case '?': case '\\': case '[': case '*'
  433. #endif    /* ATARI */
  434.  
  435.  
  436. #endif    /* UX_OS || ATARI */
  437.  
  438.  
  439.  
  440.  
  441.  
  442.  
  443.  
  444.    /* Get the next part of the filename (ie the stuff between "/"s).  The
  445.     *   parts of "/foo/*.c" are: "/", "foo", "*.c".
  446.     * Input:
  447.     * Output:
  448.     *   eval:  TRUE if part contains wildcards needing expansion.
  449.     *   word:  The part.
  450.     *   start: Points after the part (after the "/" or '\0').
  451.     * Returns:
  452.     *   TRUE: Hit the end of the filename else FALSE.
  453.     */
  454. static int get_dpart(start,word,eval) char **start, *word; int *eval;
  455. {
  456.   register char *ptr = *start;
  457.   int atend = TRUE;
  458.  
  459.   *eval = FALSE;
  460.   while (TRUE)
  461.   {
  462.     switch (*word++ = *ptr++)
  463.     {
  464.       ASLASH:
  465.         atend = FALSE;
  466.         if (*eval) word--;            /* remove trailing "/" */
  467.       case '\0': *word = '\0'; *start = ptr; return atend;
  468.       GOTTA_EVAL: *eval = TRUE; break;
  469.     }
  470.   }
  471. }
  472.  
  473.  
  474. #ifdef TEST
  475. /* **************** TEST ******************************************** */
  476.  
  477. #include "dtable.h"
  478. declare_and_init_dTable(ntable,char *);
  479.  
  480. extern char *savestr();
  481.  
  482. add_to_table(name) char *name;
  483. {
  484.   static int n = 0;
  485.  
  486.   xpand_dTable(&ntable, 1, 50, 25);
  487.   ntable.table[n++] = savestr(name);
  488.   return 0;
  489. }
  490.  
  491. char name_heap[3000];
  492. main()
  493. {
  494.   char buf[80], *zim = NULL;
  495.   int j, nopath;
  496.  
  497.   printf("Use name_heap? "); gets(buf); if (atoi(buf)) zim = name_heap;
  498.   printf("No path? "); gets(buf); nopath = atoi(buf);
  499.  
  500.   printf(": "); gets(buf);
  501.   if (fxpand(buf,FALSE,nopath,zim,add_to_table)) puts("blew up");
  502.   else
  503.   {
  504.     if (zim) printf(">%s<\n",zim);
  505.     else
  506.     {
  507.       for (j = 0; j < sizeof_dTable(&ntable); j++)
  508.     printf("table[%d]: %s\n",j,ntable.table[j]);
  509.     }
  510.   }
  511. }
  512. #endif
  513.